//
//  NMAnimatedImage.swift
//  NetEaseMusic
//
//  Created by SAGESSE on 2020/2/13.
//  Copyright © 2020 SAGESSE. All rights reserved.
//

import UIKit
import AsyncDisplayKit


class NMAnimatedImage: NSObject, ASAnimatedImageProtocol {
    
    let duration: TimeInterval
    let images: [UIImage?]
    let loop: Int

    init(_ images: [UIImage?], duration: TimeInterval, loop: Int = .max) {
        self.duration = duration
        self.images = images
        self.loop = loop
        super.init()
    }
    convenience init(_ names: [String], duration: TimeInterval, loop: Int = .max) {
        self.init(names.map({ UIImage(named: $0) }),
                  duration: duration,
                  loop: loop)
    }

        
    var coverImage: UIImage? {
        return images.first ?? nil
    }
    
    var coverImageReady: Bool {
        return true
    }
    
    var totalDuration: CFTimeInterval {
        return duration
    }
    
    var frameInterval: UInt {
        return 2
    }
    
    var frameCount: Int {
        return images.count
    }
    
    var loopCount: Int {
        return loop
    }
    
    var playbackReady: Bool {
        return true
    }
    
    var error: Error? {
        return nil
    }
    
    func image(at index: UInt) -> Unmanaged<CGImage>? {
        return images[.init(index)]?.cgImage.map {
            return Unmanaged.passRetained($0)
        }
    }
    
    func duration(at index: UInt) -> CFTimeInterval {
        return duration / .init(frameCount)
    }
    
    func clearAnimatedImageCache() {
    }
    
    var playbackReadyCallback: (() -> Void)?
}
